package com.self.chan.rocketmq;

import com.alibaba.fastjson.JSON;
import com.self.chan.model.MessagePayload;
import com.self.chan.model.ResponseEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.tio.core.Tio;
import org.tio.websocket.common.WsResponse;
import org.tio.websocket.starter.TioWebSocketServerBootstrap;

/**
 * @version v1.0
 * @ClassName: TioListenner
 * @Description:
 * @Author: Mac
 */
@Component
@Slf4j
public class TioListenner {

    @Autowired
    private TioWebSocketServerBootstrap tioWebSocketServerBootstrap;

    @StreamListener("tio_group")
    public void handleMessage(MessagePayload message){
        log.info("接收到rocketmq的消息========>{}", message == null?null:JSON.toJSONString(message));
        ResponseEntity responseEntity = new ResponseEntity();
        responseEntity.setSubbed(message.getChannel());
        responseEntity.setResult(message.getBody());
        // 推送给前端的用户就可以了
        if (StringUtils.hasText(message.getUserId()) && StringUtils.isEmpty(message.getBody())) {
            Tio.sendToUser(tioWebSocketServerBootstrap.getServerTioConfig(), message.getUserId(), responseEntity.build());
        }else if (message != null && StringUtils.hasText(message.getChannel())
                && StringUtils.isEmpty(message.getBody())){
            //推送前端
            Tio.sendToGroup(tioWebSocketServerBootstrap.getServerTioConfig(),message.getChannel(),
                    responseEntity.build());
        }
    }
}
